/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-03-07 11:26:24
 * @LastEditTime: 2023-10-18 16:29:11
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import {
  Center,
  Flex,
  IconButton,
  Image,
  Link,
  Spinner,
  Tooltip,
} from '@chakra-ui/react';
import { skipToken } from '@reduxjs/toolkit/dist/query';
import { useGetImageDTOQuery, useGetImageMetadataQuery } from '@tourfly/api';
import { RiDownload2Fill } from 'react-icons/ri';
import { useDebounce } from 'use-debounce';

import ImageMetaInfo from './ImageMetaInfo';

const ImageDetail = ({ showDetailImage }: { showDetailImage: string }) => {
  const [debouncedMetadataQueryArg, debounceState] = useDebounce(
    showDetailImage,
    500
  );

  const { currentData: imageDTO, isFetching: isDTOFetching } =
    useGetImageDTOQuery(showDetailImage ?? skipToken);

  const { currentData: metadataData, isFetching: isMetadataFetching } =
    useGetImageMetadataQuery(
      debounceState.isPending()
        ? skipToken
        : debouncedMetadataQueryArg ?? skipToken
    );

  const metadata = metadataData?.metadata;

  if (isDTOFetching || isMetadataFetching) {
    return (
      <Center h="96">
        <Spinner />
      </Center>
    );
  }

  return (
    <Flex
      w="full"
      pb="4"
      gap={2}
      direction="column"
      alignItems="center"
      justifyContent="center"
    >
      <Flex
        w="full"
        rounded="lg"
        overflow="hidden"
        direction={{ base: 'column', md: 'row' }}
      >
        <Flex w={{ base: '100%', md: '60%' }} p="2" flexDirection="column">
          <Image
            rounded="md"
            w="full"
            objectFit="contain"
            src={imageDTO?.image_url}
            style={{ imageRendering: '-webkit-optimize-contrast' }}
          />

          <Flex gap={2} justify="flex-end" alignItems="center" mt={2}>
            <Link download={imageDTO?.image_name} href={imageDTO?.image_url}>
              <Tooltip label="下载原图" hasArrow placement="top">
                <IconButton
                  color="base.700"
                  aria-label=""
                  icon={<RiDownload2Fill />}
                  backgroundColor="transparent"
                  _hover={{
                    backgroundColor: 'transparent',
                    svg: {
                      fill: 'accent.500',
                    },
                  }}
                  size="xs"
                  fontSize={20}
                />
              </Tooltip>
            </Link>
          </Flex>
        </Flex>
        <Flex
          w={{ base: '100%', md: '40%' }}
          p="2"
          gap="2"
          flexDirection="column"
        >
          <ImageMetaInfo metadata={metadata} />
        </Flex>
      </Flex>
    </Flex>
  );
};

export default ImageDetail;
